package com.sangmo.fts.process.storage.service;

import com.sangmo.boot.framework.common.errors.ServiceException;
import com.sangmo.boot.framework.common.errors.StandardErrors;
import com.sangmo.boot.framework.data.filter.PageResult;
import com.sangmo.boot.framework.data.filter.PageSearch;
import com.sangmo.boot.framework.data.filter.ValueFilter;
import com.sangmo.boot.framework.plugin.dataview.crud.service.DelegateViewService;
import com.sangmo.boot.framework.plugin.dataview.crud.service.ViewService;
import com.sangmo.fts.process.storage.interfaces.CsfWaybillReceiveRequest;
import com.sangmo.fts.process.storage.model.CsfWaybill;
import com.sangmo.fts.process.storage.model.CsfWaybillItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class CsfWaybillService extends DelegateViewService<CsfWaybill> {

    @Autowired
    private CsfWaybillEntityService csfWaybillEntityService;

    @Autowired
    private CsfWaybillItemEntityService csfWaybillItemEntityService;

    @Override
    protected ViewService<CsfWaybill> getEntityService() {
        return csfWaybillEntityService;
    }

    public void ship(Long id) {
        CsfWaybill waybill = this.get(id);
        if (!CsfWaybill.States.PENDING.equals(waybill.getState())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.csfWaybill.has.shipped");
        }
        waybill.setState(CsfWaybill.States.DISPATCHED);
        this.save(waybill);
    }

    public PageResult<CsfWaybillItem> listItemsByPage(Long waybillId, PageSearch ps) {
        ps.getFilters().add(new ValueFilter("waybillId", ValueFilter.OP_EQ, waybillId));
        return csfWaybillItemEntityService.search(ps);
    }

    public List<CsfWaybillItem> listItemsByWaybillId(Long waybillId) {
        return csfWaybillItemEntityService.listByWaybillId(waybillId);
    }

    public void receive(Long id, CsfWaybillReceiveRequest request) {
        CsfWaybill waybill = this.get(id);
        if (!CsfWaybill.States.DISPATCHED.equals(waybill.getState())) {
            throw new ServiceException(StandardErrors.CLIENT_ERROR.getStatus(), "error.csfWaybill.has.received");
        }
        waybill.setState(CsfWaybill.States.RECEIVED);
        waybill.setReceiptTime(request.getReceiptTime());
        waybill.setReceiptPlace(request.getReceiptPlace());
        this.save(waybill);
    }

    public PageResult<CsfWaybill> selection(PageSearch ps) {
        ps.getFilters().add(new ValueFilter("state", ValueFilter.OP_EQ, CsfWaybill.States.RECEIVED));
        return super.search(ps);
    }

}
